package com.onstar.cn.framework.network.http;

import com.onstar.cn.common.error.CommErrorUtils;
import com.onstar.cn.common.exception.HttpException;
import com.onstar.cn.common.util.CommonUtil;
import com.onstar.cn.framework.network.HttpInjectUtils;
import com.onstar.cn.framework.network.entity.RequestEntity;

public class ByteSender {
	/**
	 * send request,Receive the response
	 * 
	 * @param requestEntity
	 * @param responseHandler
	 */
	public void send(RequestEntity requestEntity, ByteResponseHandler responseHandler) {
		String tag = "Sender";
		if (!CommonUtil.isNull(requestEntity) && !CommonUtil.isNull(requestEntity.getUrl())) {
			ByteRequestThread thread = new ByteRequestThread(requestEntity, responseHandler);
			thread.setTimeout(requestEntity.getTimeout());
			try {
				tag = requestEntity.getUrl().substring(requestEntity.getUrl().lastIndexOf("/") + 1,
						requestEntity.getUrl().indexOf("?") > 0 ? requestEntity.getUrl().indexOf("?")
								: requestEntity.getUrl().length());
				thread.setTag(tag);
			} catch (Exception e) {
				e.printStackTrace();
			}
			new Thread(thread).start();
		} else {
			CommErrorUtils error = CommErrorUtils.defaultError();
			responseHandler.onError(tag, new HttpException(error.getErrorCode(), error.getErrorMsg()));
		}
	}

	/**
	 * send request,Don't receive the response
	 * 
	 * @param requestEntity
	 */
	public void send(RequestEntity requestEntity) {
		if (!CommonUtil.isNull(requestEntity) && !CommonUtil.isNull(requestEntity.getUrl())) {
			send(requestEntity, null);
		}
	}

	public void send(String url, Class<?> clazz, ByteResponseHandler responseHandler) {
		RequestEntity request = new RequestEntity();
		request.setUrl(url);
		request = HttpInjectUtils.injectHttp(clazz, request);
		send(request, responseHandler);
	}

	public void send(String url, Class<?> clazz) {
		RequestEntity request = new RequestEntity();
		request.setUrl(url);
		request = HttpInjectUtils.injectHttp(clazz, request);
		send(request);
	}

	public void send(RequestEntity request, ByteResponseHandler responseHandler, Class<?> clazz) {
		request = HttpInjectUtils.injectHttp(clazz, request);
		send(request, responseHandler);
	}

	public void send(RequestEntity request, ByteResponseHandler responseHandler, Class<?> clazz, String method) {
		request = HttpInjectUtils.injectHttp(clazz, method, request);
		send(request, responseHandler);
	}
	
	public void send(RequestEntity request, ByteResponseHandler responseHandler, Class<?> clazz, String method, Class<?>... paramClazz) {
		request = HttpInjectUtils.injectHttp(clazz, method, request, paramClazz);
		send(request, responseHandler);
	}

	public void send(String url, String method, Class<?> clazz) {
		RequestEntity request = new RequestEntity();
		request.setUrl(url);
		request = HttpInjectUtils.injectHttp(clazz, method, request);
		send(request);
	}
}
